﻿#include "DataPack.h"
#include <vector>
namespace Network
{

	using namespace  std;
	void DataPack::Alloc(unsigned int size)
	{
		this->size = size;
		if (buffer)
		{
			delete[]buffer;
			buffer = nullptr;
		}
		buffer = new char[this->size];
	}

	void DataPack::DeAlloc()
	{
		if (buffer)
		{
			delete[]buffer;
			buffer = nullptr;
			this->size = 0;
		}
	}

	DataPack::~DataPack()
	{
		this->DeAlloc();
	}

	DataPack*  DataPack::CreateWithCmd(Cmd*cmd, bool encode)
	{
		return nullptr;
	}

	DataPack* DataPack::CreateWithMask(int mask)
	{
		DataPack * ret = new DataPack;
		if (mask < 0)
		{
			ret->_isEncode = true;
		}
		else
		{
			ret->_isEncode = false;
		}
		ret->size = abs(mask);
		return ret;
	}

	DataPack* DataPack::CreateWithString(const std::string &s, bool encode)
	{
		DataPack * ret = new DataPack;


		unsigned int len = s.size() + 1;
		std::vector <char> buf;
		for (int ii = 0; ii < sizeof(unsigned int); ii++)
		{
			char  *addr = (char*)(&len);
			buf.push_back(*(addr + ii));
		}
		for (int ii = 0; ii < s.size(); ii++)
		{
			buf.push_back(s.at(ii));
		}
		buf.push_back('\0');

		ret->size = buf.size();
		ret->Alloc(ret->size);
		memcpy(ret->buffer, &buf[0], buf.size());
		ret->_isEncode = encode;
		return ret;
	}
	void DataPack::Encode()
	{
		//	int ret = compress(0, 0, 0, 0);
	}

	void DataPack::Decode()
	{
		//int ret = uncompress(0, 0, 0, 0);
	}
}